/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.utils.HibernateUtil;
import Controllers.utils.URLUtils;
import DAO.ProductsManager;
import Model.BasketLine;
import Model.ProductBasket;
import Model.Produit;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Anthares
 */
public class BasketServlet extends BaseServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request  servlet request
     * @param response servlet response
     * <p/>
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException      if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String locale = getLocaleString(request);
        HashMap<String, String> requestedRessource = URLUtils.getRequestedRessource(getServletContext(), request);
        String action = requestedRessource.get("action");

        if(action != null){
            if(action.equals("add")){
                addAction(request, locale, response);
            } else if(action.equals("edit")){
                editAction(request, locale, response);
            } else if(action.equals("remove")){
                removeAction(request, locale, response);
            } else if(action.equals("clear")){
                clearAction(request, locale, response);
            } else {
                handleError(404, request, response);
            }
        }
        dispatch("/basket.jsp", request, response);
    }

    private void addAction(HttpServletRequest request, String locale, HttpServletResponse response) throws IOException, ServletException {
        String prodIdString = request.getParameter("prodId");
        String quantityString = request.getParameter("quantity");
        if(prodIdString != null && quantityString != null){
            int prodId;
            int quantity;

            ProductBasket basket;

            try{
                prodId = Integer.parseInt(prodIdString);
                quantity = Integer.parseInt(quantityString);

                if(prodId > 0 && quantity > 0){
                    HttpSession sess = request.getSession();
                    basket = (ProductBasket) sess.getAttribute("basket");
                    HashMap<Integer, BasketLine> lines = basket.getLines();
                    BasketLine line = lines.get(prodId);
                    if(line == null){
                        Produit prod = new ProductsManager(HibernateUtil.getSessionFactory(), locale).getProductByID(prodId);
                        line = new BasketLine(quantity, prod);
                        basket.getLines().put(line.getKey(), line);
                    } else {
                        line.addQuantity(quantity);
                    }
                } else {
                    handleError(404, request, response);
                }
            } catch(NumberFormatException e){
                handleError(403, request, response);
            } catch(NullPointerException e){
                basket = new ProductBasket();
                request.getSession().setAttribute("basket", basket);
                addAction(request, locale, response);
            }
        } else {
            dispatch("/shop", request, response);
        }
    }

    private void editAction(HttpServletRequest request, String locale, HttpServletResponse response) throws ServletException, IOException {
        String prodIdString = request.getParameter("prodId");
        String quantityString = request.getParameter("quantity");
        if(prodIdString != null && quantityString != null){
            int prodId;
            int quantity;

            ProductBasket basket;

            try{
                prodId = Integer.parseInt(prodIdString);
                quantity = Integer.parseInt(quantityString);
                if(prodId > 0 && quantity > 0){
                    HttpSession sess = request.getSession();
                    basket = (ProductBasket) sess.getAttribute("basket");
                    BasketLine line = basket.getLines().get(prodId);
                    if(line != null){
                        line.setQuantity(quantity);
                    }
                }
            } catch(NumberFormatException e){
                handleError(403, request, response);
            } catch(NullPointerException e){
                basket = new ProductBasket();
                request.getSession().setAttribute("basket", basket);
            }
        } else {
            dispatch("/shop", request, response);
        }
    }

    private void removeAction(HttpServletRequest request, String locale, HttpServletResponse response) throws ServletException, IOException {
        String prodIdString = request.getParameter("prodId");
        if(prodIdString != null){
            int prodId;

            ProductBasket basket;
            try{
                prodId = Integer.parseInt(prodIdString);

                if(prodId > 0){
                    HttpSession sess = request.getSession();
                    basket = (ProductBasket) sess.getAttribute("basket");
                    BasketLine line = basket.getLines().get(prodId);
                    if(line != null){
                        basket.getLines().remove(prodId);
                    }
                }
            } catch(NumberFormatException e){
                handleError(403, request, response);
            } catch(NullPointerException e){
                basket = new ProductBasket();
                request.getSession().setAttribute("basket", basket);
            }
        } else {
            dispatch("/shop", request, response);
        }
    }

    private void clearAction(HttpServletRequest request, String locale, HttpServletResponse response) {
        HttpSession sess;
        synchronized(sess = request.getSession()){
            ProductBasket basket = (ProductBasket) sess.getAttribute("basket");
            basket.clear();
        }
    }
}
